<template>
  <q-page :class="$q.screen.xs ? '' : 'q-pa-md'">
    <q-banner dense class="bg-primary text-white" v-if="userInfo.tenant_id == 0">
      <filterSelect class="bg-white" :field="tenant" />
    </q-banner>

    <q-splitter
      :limits="[0, 100]"
      v-model="splitterModel"
      :horizontal="$q.screen.xs"
    >
      <template v-slot:before>
        <q-tabs
          v-model="tab"
          class="text-grey"
          active-color="primary"
          indicator-color="primary"
        >
          <q-tab name="user" label="用户" />
          <q-tab name="role" label="角色" />
        </q-tabs>

        <q-separator />

        <q-tab-panels v-model="tab" animated transition-prev="fade" transition-next="fade">
          <q-tab-panel name="user">
            <q-table
              title="用户信息"
              :rows="user.data"
              :columns="user.columns"
              row-key="id"
              v-model:pagination="user.pagination"
              :loading="user.loading"
              :filter="user.filter"
              :rows-per-page-options="[0]"
              @request="onUserRequest"
              binary-state-sort
              selection="single"
              v-model:selected="user.selected"
              @row-click="rowClick"
              :style="$q.screen.xs ? '' : 'max-height: calc(100vh - 100px)'"
              class="my-sticky-virtscroll-table"
            >
              <template v-slot:top>
                <div class="flex full-width q-gutter-xs">
                  <q-input outlined dense debounce="300" v-model="user.filter" placeholder="搜索 用户信息...">
                    <template v-slot:append>
                      <q-icon v-if="user.filter" name="close" @click="user.filter = ''" class="cursor-pointer" />
                      <q-icon name="search" />
                    </template>
                  </q-input>
                  <q-space />
                  <q-btn label="新增用户" color="secondary" icon="add" @click="editUser()">
                  </q-btn>
                </div>
              </template>
              <template v-slot:body-cell-nickname="props">
                <q-td :props="props" :class="!props.row.state && 'text-grey'">
                  <div>{{ props.row.nickname }}</div>
                  <q-badge v-if="props.row.wx_userid" color="green">微信:{{props.row.wx_name}}</q-badge>
                  <q-badge v-if="props.row.dd_userid" color="blue">钉钉:{{props.row.dd_name}}</q-badge>
                </q-td>
              </template>
              <template v-slot:body-cell-state="props">
                <q-td :props="props" :class="!props.row.state?'text-grey':'text-primary text-bold'">
                  {{ props.row.state?'启用':'停用' }}
                </q-td>
              </template>
              <template v-slot:body-cell-login_count="props">
                <q-td :props="props" :class="!props.row.state && 'text-grey'">
                  {{ props.row.login_count }}
                </q-td>
              </template>
              <template v-slot:body-cell-operate="props">
                <q-td class="q-gutter-sm" :props="props">
                  <q-btn round color="secondary" icon="edit" size="sm" @click="editUser(props.row)">
                    <q-tooltip>修改用户信息</q-tooltip>
                  </q-btn>
                  <q-btn round color="grey" icon="delete" size="sm" @click="deleteUser(props.row)" v-if="!isSuper(props.row.id)">
                    <q-tooltip>删除用户</q-tooltip>
                  </q-btn>
                </q-td>
              </template>
            </q-table>
          </q-tab-panel>

          <q-tab-panel name="role">
            <div class="q-py-sm">
              <q-banner inline-actions rounded class="bg-orange text-white">
                <template v-slot:avatar>
                  <q-icon name="info" color="white" />
                </template>
                重要提示：请为不同的角色定义不同的权限.
              </q-banner>
            </div>

            <q-table
              title="角色信息"
              :rows="role.data"
              :columns="role.columns"
              row-key="id"
              v-model:pagination="role.pagination"
              :loading="role.loading"
              :filter="role.filter"
              :rows-per-page-options="[0]"
              @request="onRoleRequest"
              binary-state-sort
              selection="single"
              v-model:selected="role.selected"
              @row-click="rowClick"
              :style="$q.screen.xs ? '' : 'max-height: calc(100vh - 100px)'"
              class="my-sticky-virtscroll-table"
              virtual-scroll
            >
              <template v-slot:top>
                <div class="flex full-width q-gutter-xs">
                  <q-input outlined dense debounce="300" v-model="role.filter" placeholder="搜索 角色信息...">
                    <template v-slot:append>
                      <q-icon v-if="role.filter" name="close" @click="role.filter = ''" class="cursor-pointer" />
                      <q-icon name="search" />
                    </template>
                  </q-input>
                  <q-space />
                  <q-btn label="新增角色" color="secondary" icon="add" @click="editRole()">
                  </q-btn>
                </div>
              </template>
              <template v-slot:body-cell-operate="props">
                <q-td class="q-gutter-sm" :props="props">
                  <q-btn round color="secondary" icon="edit" size="sm" @click="editRole(props.row)" v-if="canEditRole(props.row)">
                    <q-tooltip>修改角色信息</q-tooltip>
                  </q-btn>
                  <q-btn round color="grey" icon="delete" size="sm" @click="deleteRole(props.row)" v-if="canEditRole(props.row)">
                    <q-tooltip>删除角色</q-tooltip>
                  </q-btn>
                </q-td>
              </template>
              <template v-slot:body-cell-role_name="props">
                <q-td class="q-gutter-sm" :props="props">
                  <div :class="props.row.hash || 'text-red'">
                    {{ props.value }}
                  </div>
                  <q-chip v-if="!props.row.hash" style="margin: 0;" dense size="xs" color="red" text-color="white" icon="alarm" label="请重新分配权限" />
                </q-td>
              </template>
            </q-table>
          </q-tab-panel>
        </q-tab-panels>
      </template>

      <template v-slot:separator v-if="!$q.screen.xs">
        <q-avatar color="primary" text-color="white" size="40px" icon="drag_indicator" />
      </template>

      <template v-slot:after>
        <q-scroll-area style="height: calc(100vh - 100px);">
          <q-markup-table>
            <thead>
              <tr>
                <th :colspan="2 + menuInfo.rightItem.length">
                  <div class="row q-gutter-x-md">
                    <div class="q-table__title">权限分配</div>
                    <!-- <q-btn color="primary" flat size="sm" label="权限复制给..." @click="showRightCopy" v-if="tab === 'user'" :disable="user.selected.length==0" /> -->
                    <!-- <q-btn color="info" flat size="sm" label="设置角色" @click="showSetRole" v-if="tab === 'user'" :disable="user.selected.length==0" /> -->
                    <q-btn-dropdown color="primary" size="sm" flat label="权限复制给...">
                      <q-list>
                        <q-item clickable v-close-popup @click="showRightCopy('user')">
                          <q-item-section>
                            <q-item-label>用户</q-item-label>
                          </q-item-section>
                        </q-item>

                        <q-item clickable v-close-popup @click="showRightCopy('role')" v-if="canCopyToRole">
                          <q-item-section>
                            <q-item-label>角色</q-item-label>
                          </q-item-section>
                        </q-item>
                      </q-list>
                    </q-btn-dropdown>
                  </div>
                </th>
              </tr>
              <tr>
                <th>分类</th>
                <th>菜单</th>
                <th v-for="right in menuInfo.rightItem" :key="right.name">{{right.label}}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in menuInfo.pureMenu" :key="item.name">
                <td v-if="!item.behind" :rowspan="item.parent && catalog[item.parent] && catalog[item.parent].children" class="text-center">
                  {{!item.behind && item.parent && catalog[item.parent] ? catalog[item.parent].caption : ''}}
                </td>
                <td class="text-center">{{item.caption}}</td>
                <td v-for="right in menuInfo.rightItem" :key="right.name" class="text-center">
                  <q-toggle
                    color="blue-7"
                    :disable="isSuperRight(item.name, right.name)"
                    v-if="item.right[right.name] !== undefined"
                    v-model="item.right[right.name]"
                    :label="item.right[right.name]?right.switch[1]:right.switch[0]"
                    @update:model-value="changeRight(item, right.name)"
                  />
                </td>
              </tr>
            </tbody>
          </q-markup-table>
        </q-scroll-area>
      </template>
    </q-splitter>

    <dialogSelectTable ref="copyRightDialog" :config="copyDialogConfig.current" @submit="confirmRightCopy" size="md" />

    <dialogForm ref="userForm" :config="user.dialogConfig" @submit="saveUser">
      <div class="col-12 text-center shadow-4 q-py-sm" v-if="user.dialogConfig.fields.id.value > 0">
        <p>注册日期：{{regTimeInfo}}</p>
        <p>登录次数：{{user.selected[0].login_count|| 0}}</p>
      </div>
    </dialogForm>

    <dialogForm ref="roleForm" :config="role.dialogConfig" @submit="saveRole" />
  </q-page>
</template>

<script>
import { defineComponent } from 'vue';
import { date, useMeta } from 'quasar';
import { mapState } from 'pinia';
import { useStore } from 'stores/store';
import filterSelect from 'components/FilterSelect.vue';
import dialogSelectTable from 'components/DialogSelectTable.vue';
import dialogForm from 'components/DialogInputForm.vue';
import md5 from 'md5';

export default defineComponent({
  name: 'users',
  components: {
    filterSelect,
    dialogSelectTable,
    dialogForm
  },
  inject: ['confirmBox', 'sendCooperation'],
  setup (props, context) {
    const $store = useStore();
    useMeta({
      title: `人员权限 - ${$store.siteConfig.appName} - 木多鱼系列`
    });
  },
  data () {
    const self = this;
    return {
      user: {
        filter: null,
        loading: false,
        pagination: {
          sortBy: 'id',
          descending: true,
          page: 1,
          rowsPerPage: 50,
          rowsNumber: 0
        },
        data: [],
        columns: [
          { name: 'operate', label: '操作', align: 'center' },
          { name: 'nickname', label: '用户名', field: 'nickname', sortable: true, align: 'center' },
          { name: 'state', label: '状态', field: 'state', align: 'center' },
          { name: 'role_name', label: '角色', field: 'role_name', sortable: true, align: 'center' },
          { name: 'tel', label: '电话', field: 'tel', align: 'center' },
          { name: 'login_count', label: '登录次数', field: 'login_count', align: 'center' }
        ],
        selected: [],

        dialogConfig: {
          title: '',
          fields: {
            id: { value: '' },
            nickname: { type: 'input', label: '用户名 *', value: '', rules: [val => !!val || '用户名不能为空', this.checkUserName] },
            password: { type: 'input', label: '密码', value: '', password: true, hint: '留空不修改密码。默认：mdy123456', rules: [this.checkPassword] },
            role: { type: 'select', label: '角色', value: '', options: [], readonly: false },
            tel: { type: 'input', label: '电话', value: '' },
            state: { type: 'toggle', label: '状态', value: '', leftLabel: true, trueValue: 1, falseValue: 0, trueLabel: '启用', falseLabel: '禁用' },
            from_type: { value: '' }, // 从哪里新增的
            from_id: { value: '' } // 源头id
          }
        }
      },

      catalog: {},
      menuInfo: { menu: [], rightItem: [], pureMenu: [] },
      rightsTemplate: {},
      splitterModel: 40,
      copyDialogConfig: {
        current: {},
        toUser: {
          title: '复制同样权限给用户',
          api: '/c2/manager/user/userList',
          search: {
            tenant_id: { value: '' },
            filter: { type: 'input', label: '用户信息', value: '' }
          },
          table: {
            multiple: true,
            columns: [
              { name: 'id', field: 'id', visible: false },
              { name: 'nickname', label: '用户名', field: 'nickname', align: 'center' },
              { name: 'department_name', label: '部门', field: 'department_name', align: 'center' },
              { name: 'tel', label: '电话', field: 'tel', align: 'center' },
              { name: 'state', label: '状态', field: 'state', align: 'center' },
              { name: 'login_count', label: '登录次数', field: 'login_count', align: 'center' }
            ]
          }
        },
        toRole: {
          title: '复制同样权限给角色',
          api: '/c2/manager/user/roleList',
          search: {
            tenant_id: { value: '' },
            filter: { type: 'input', label: '角色名称', value: '' }
          },
          table: {
            multiple: false,
            columns: [
              { name: 'id', field: 'id', value: '', visible: false },
              { name: 'role_name', label: '角色名称 *', field: 'role_name', align: 'center' },
              { name: 'user_count', label: '用户数量', field: 'user_count', align: 'center' }
            ]
          }
        },
        toType: ''
      },
      tab: 'user',
      role: {
        filter: null,
        loading: false,
        pagination: {
          sortBy: 'id',
          descending: true,
          page: 1,
          rowsPerPage: 50,
          rowsNumber: 0
        },
        data: [],
        columns: [
          { name: 'operate', label: '操作', align: 'center' },
          { name: 'role_name', label: '角色名称', field: 'role_name', sortable: true, align: 'center', rules: [val => !!val || '角色名称不能为空', self.checkRoleName] },
          { name: 'user_count', label: '用户数量', field: 'user_count', align: 'center' },
          { name: 'repeat_count', label: '权限重复', field: 'repeat_count', align: 'center', format: val => val > 1 ? `${val - 1}个` : '无' }
        ],
        selected: [],

        dialogConfig: {
          title: '',
          fields: {
            id: { value: '' },
            role_name: { type: 'input', label: '角色名称 *', rules: [val => !!val || '角色名称不能为空'], value: '' }
          }
        }
      },
      tenant: {
        label: '租户',
        value: '',
        selected: [],
        options: [{ value: 0, label: '系统管理' }],
        clearable: false
      }
    }
  },
  mounted () {
    this.$axios.post('/c/system/getDataDict', { types: 'tenant' }).then(({ data }) => {
      this.tenant.options.push(...data.tenant);
      this.tenant.value = this.userInfo.tenant_id;
    });
  },
  methods: {
    async refreshMenu () {
      const type = Number(this.tenant.value) > 0 ? 't' : 'm';
      const { menu } = (await this.$axios.get('/c/system/getGeneralConfig', { params: { type } })).data;
      this.menuInfo = menu;
      this.menuInfo.pureMenu = menu.menu.filter(m => m.type === 'menu'); // 过滤出菜单项
      // 过滤出菜单项
      this.catalog = {};
      for (const item of menu.menu) {
        if (item.type === 'label') {
          this.catalog[item.name] = { caption: item.caption, children: 0 };
        }
      }

      // 统计子项数量
      for (const c in this.catalog) {
        this.catalog[c].children = menu.menu.filter(m => m.parent == c).length;
      }

      // 标识第二个开始的子项
      for (let i = this.menuInfo.pureMenu.length - 1; i > 0; i--) {
        if (this.menuInfo.pureMenu[i - 1].parent == this.menuInfo.pureMenu[i].parent) {
          this.menuInfo.pureMenu[i].behind = true;
        }
      }

      // 生成权限模块
      this.rightsTemplate = {};
      this.menuInfo.pureMenu.forEach(m => {
        this.rightsTemplate[m.name] = Object.assign({}, m.right);
      });
      this.refreshRoleOpt();
    },
    search () {
      if (this.tab === 'user') {
        this.onUserRequest({
          pagination: this.user.pagination,
          filter: this.user.filter
        });
      } else {
        this.onRoleRequest({
          pagination: this.role.pagination,
          filter: this.role.filter
        });
      }
    },
    refreshRoleOpt () {
      this.$axios.post('/c2/manager/user/roleList', { filter: { tenant_id: this.tenant.value } }).then(({ data }) => {
        this.user.dialogConfig.fields.role.options = data.data.filter(v => v.hash).map(v => ({ value: v.id, label: v.role_name }));
      });
    },
    onUserRequest (props) {
      const { page, rowsPerPage, sortBy, descending } = props.pagination;
      const filter = props.filter || {};
      filter.tenant_id = this.tenant.value;

      this.user.loading = true;

      const startRow = (page - 1) * rowsPerPage;
      const count = rowsPerPage;

      this.$axios.post('/c2/manager/user/userList', { startRow, count, filter, sortBy, descending }).then(({ data }) => {
        this.user.pagination.rowsNumber = data.rowsNumber;
        this.user.data = data.data;

        this.user.pagination.page = page;
        this.user.pagination.sortBy = sortBy;
        this.user.pagination.descending = descending;
        this.user.loading = false;
        if (this.user.selected.length === 0 && data.data.length > 0) {
          this.user.selected = [data.data[0]];
        }
        if (this.user.selected.length > 0) {
          setTimeout(() => { this.parseRight(this.user.selected[0].rights) }, 50);
          // this.parseRight(this.user.selected[0].rights);
        }
      });
    },
    editUser (row, from) {
      this.user.dialogConfig.fields.role.readonly = false;
      if (!row) {
        this.user.dialogConfig.title = '新增用户';
        this.user.dialogConfig.fields.id.value = -1;
        this.user.dialogConfig.fields.nickname.value = '';
        this.user.dialogConfig.fields.password.value = '';
        this.user.dialogConfig.fields.password.hint = '留空默认：mdy123456';
        this.user.dialogConfig.fields.tel.value = '';
        this.user.dialogConfig.fields.state.value = 1;
        this.user.dialogConfig.fields.from_type.value = '';
        this.user.dialogConfig.fields.from_id.value = '';
        // 有源头
        if (from) {
          for (const key of Object.keys(from)) {
            if (this.user.dialogConfig.fields[key]) {
              this.user.dialogConfig.fields[key].value = from[key];
            }
          }
          if (from.from_type === 'cus') {
            this.user.dialogConfig.fields.role.readonly = true;
          }
        }
      } else {
        this.user.dialogConfig.title = '修改用户';
        this.user.dialogConfig.fields.id.value = row.id;
        this.user.dialogConfig.fields.nickname.value = row.nickname;
        this.user.dialogConfig.fields.password.value = '';
        this.user.dialogConfig.fields.password.hint = '留空不修改密码';
        this.user.dialogConfig.fields.tel.value = row.tel;
        this.user.dialogConfig.fields.state.value = row.state;
        this.user.dialogConfig.fields.from_type.value = '';
        this.user.dialogConfig.fields.from_id.value = '';
      }
      this.$refs.userForm.show();
    },
    deleteUser (row) {
      const self = this;
      this.confirmBox('删除', '确定删除该用户吗？').then(confirm => {
        if (confirm) {
          self.$axios.post('/c2/manager/user/saveUser', { mode: 'delete', id: row.id }).then(({ data }) => {
            if (data.result === 'fail') {
              self.$q.notify({
                message: data.message || '删除失败',
                color: 'negative',
                icon: 'error',
                position: 'top',
                timeout: 2000
              });
            } else {
              self.$q.notify({
                message: '删除成功',
                color: 'secondary',
                icon: 'done',
                position: 'top',
                timeout: 2000
              });
              self.search();
              // 发送协同，刷新字典
              self.sendCooperation({ type: 'refresh_user' }, row.id);
              self.sendCooperation({ type: 'refresh_dict', data: ['user'] });
            }
          });
        }
      });
    },
    rowClick (evt, row) {
      this[this.tab].selected = [row];
    },
    checkUserName (val) {
      const self = this;
      return new Promise((resolve, reject) => {
        let len = 0;
        for (let i = 0; i < val.length; i++) {
          val.charCodeAt(i) < 256 ? (len += 1) : (len += 2);
        }
        if (len < 4) {
          resolve('用户名过短，至少2个中文或4个英文字符');
        } else {
          self.$axios.post('/c/system/checkRepeatCode', { code: 'u', values: { nickname: val }, exclude: ['id', this.user.dialogConfig.fields.id.value] }).then(res => {
            resolve(res.data ? '用户名重复' : null);
          });
        }
      });
    },
    checkRoleName (val) {
      const self = this;
      return new Promise((resolve, reject) => {
        self.$axios.post('/c/system/checkRepeatCode', { code: 'r', values: { role_name: val }, exclude: ['id', this.role.dialogConfig.fields.id.value] }).then(res => {
          resolve(res.data ? '角色名称重复' : null);
        });
      });
    },
    checkPassword (val) {
      return new Promise((resolve, reject) => {
        const reg = /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,20}$/;
        if (val && val.length > 0) resolve(reg.test(val) || '需要6~10位的 数字+字母 或 字母+特殊字符 或 特殊字符+数字');
        else resolve(true);
      });
    },
    saveUser (formData) {
      if (!formData) return;

      const id = formData.id;
      delete formData.id;
      if (formData.password) formData.password = md5(formData.password);
      formData.tenant_id = this.tenant.value;

      const mode = id < 0 ? 'add' : 'edit';

      this.$axios.post('/c2/manager/user/saveUser', { mode, id, formData }).then(({ data }) => {
        if (data.result === 'fail') {
          this.$q.notify({
            message: data.message || '保存失败',
            color: 'negative',
            icon: 'error',
            position: 'top',
            timeout: 2000
          });
        } else {
          this.$q.notify({
            message: '保存成功',
            color: 'secondary',
            icon: 'done',
            position: 'top',
            timeout: 2000
          });

          if (mode === 'add') {
            this.user.selected = [];
          }
          this.search();
          // 发送协同，刷新用户信息
          this.sendCooperation({ type: 'refresh_user' }, id);
          this.sendCooperation({ type: 'refresh_dict', data: ['user'] });
        }
      });
    },
    parseRight (rights) { // 解析权限
      if (!rights || Object.keys(rights).length === 0) return;

      this.menuInfo.pureMenu.forEach(item => {
        for (const r in item.right) {
          item.right[r] = rights[item.name] === undefined ? this.rightsTemplate[item.name][r] : !!rights[item.name][r];
        }
      });
    },
    changeRight (menu, rightName) {
      // 功能一关，后面的所有功能都关
      if (rightName === 'func' && !menu.right.func) {
        Object.keys(menu.right).forEach(key => {
          menu.right[key] = false;
        });
      }
      // 有权限变动，保存数据
      const self = this;
      const rights = {};
      this.menuInfo.pureMenu.forEach(m => {
        rights[m.name] = Object.assign({}, m.right);
      });

      if (this.tab === 'user' && this.user.selected.length > 0) { // 用户的权限变动
        this.user.selected[0].rights = JSON.parse(JSON.stringify(rights));

        this.$axios.post('/c2/manager/user/saveUserRights', {
          id: this.user.selected[0].id,
          rights: this.user.selected[0].rights
        }).then(({ data }) => {
          // 发送协同，刷新用户信息
          this.sendCooperation({ type: 'refresh_user' }, self.user.selected[0].id);
          this.sendCooperation({ type: 'refresh_dict', data: ['user'] });

          this.search();
        });
      } else if (this.tab === 'role' && this.role.selected.length > 0) { // 角色的权限变动
        const newRights = JSON.parse(JSON.stringify(rights));

        this.$axios.post('/c2/manager/user/saveRoleRights', {
          id: this.role.selected[0].id,
          rights: newRights,
          tenant_id: this.tenant.value
        }).then(({ data }) => {
          if (data.result === 'fail') {
            this.$q.notify({
              message: data.message || '角色权限设置失败',
              color: 'negative',
              icon: 'error',
              position: 'top',
              timeout: 2000
            });
          } else {
            // 发送协同，刷新用户信息
            if (this.role.selected.user_detail && this.role.selected.user_detail.length > 0) {
              this.role.selected.user_detail.forEach(row => {
                this.sendCooperation({ type: 'refresh_user' }, row.id);
              });
              this.sendCooperation({ type: 'refresh_dict', data: ['user'] });
            }
            this.role.selected[0].rights = newRights;
          }

          this.search();
        });
      }
    },
    isSuper (id) { // 是否为超级管理员
      if (id === 1) return true;

      if (this.menuInfo.super && this.menuInfo.super.id) {
        let superId = this.menuInfo.super.id;
        if (typeof superId !== 'object') superId = [superId];
        return superId.indexOf(id) >= 0;
      } else {
        return false
      }

      // return id == this.menuInfo.super.id;
    },
    isSuperRight (menu, func) { // 是否为超级管理员的权限
      if (this.user.selected.length > 0) {
        if (this.isSuper(this.user.selected[0].id)) {
          return this.menuInfo.super.required.some(r => r.name == menu && r.right.indexOf(func) > -1);
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    showRightCopy (type) {
      if (type === 'user') {
        this.copyDialogConfig.toUser.search.tenant_id.value = this.tenant.value;
        this.copyDialogConfig.current = this.copyDialogConfig.toUser;
      } else {
        this.copyDialogConfig.toRole.search.tenant_id.value = this.tenant.value;
        this.copyDialogConfig.current = this.copyDialogConfig.toRole;
      }
      this.copyDialogConfig.toType = type;
      this.$refs.copyRightDialog.show();
    },
    confirmRightCopy (data) { // 确认复制权限
      if (data && data.length > 0) {
        const from = {
          type: this.tab,
          id: this[this.tab].selected[0].id
        };
        const to = {
          type: this.copyDialogConfig.toType,
          id: data.map(v => v.id)
        }
        this.$axios.post('/c2/manager/user/copyRightsTo', { from, to, tenant_id: this.tenant.value }).then(res => {
          if (res.data.result === 'fail') {
            this.$q.notify({
              message: res.data.message || '复制失败',
              color: 'negative',
              icon: 'error',
              position: 'top',
              timeout: 2000
            });
          } else {
            this.$q.notify({
              message: '复制成功',
              color: 'secondary',
              icon: 'done',
              position: 'top',
              timeout: 2000
            });
            // 发送协同，刷新用户信息
            if (this.copyDialogConfig.toType === 'user') {
              data.forEach(row => {
                this.sendCooperation({ type: 'refresh_user' }, row.id);
              });
              this.sendCooperation({ type: 'refresh_dict', data: ['user'] });
            }
          }

          this.search();
        });
      }
    },
    onRoleRequest (props) {
      const { page, rowsPerPage, sortBy, descending } = props.pagination;
      const filter = props.filter || {};
      filter.tenant_id = this.tenant.value;
      this.role.loading = true;

      const startRow = (page - 1) * rowsPerPage;
      const count = rowsPerPage;

      this.$axios.post('/c2/manager/user/roleList', { startRow, count, filter, sortBy, descending }).then(({ data }) => {
        this.role.pagination.rowsNumber = data.rowsNumber;
        this.role.data = data.data;

        this.role.pagination.page = page;
        this.role.pagination.sortBy = sortBy;
        this.role.pagination.descending = descending;
        this.role.loading = false;
        if (this.role.selected.length == 0 && data.data.length > 0) {
          this.role.selected = [data.data[0]];
        }
        if (this.role.selected.length > 0) {
          setTimeout(() => { this.parseRight(this.role.selected[0].rights) }, 50);
          // this.parseRight(this.role.selected[0].rights);
        }
      });
    },
    canEditRole (row) {
      return row.id >= 10; // 非系统保留角色id才允许修改
    },
    editRole (row) {
      if (!row) {
        this.role.dialogConfig.title = '新增角色';
        this.role.dialogConfig.fields.id.value = -1;
        this.role.dialogConfig.fields.role_name.value = '';
      } else {
        this.role.dialogConfig.title = '修改角色';
        this.role.dialogConfig.fields.id.value = row.id;
        this.role.dialogConfig.fields.role_name.value = row.role_name;
      }
      this.$refs.roleForm.show();
    },
    deleteRole (row) {
      const self = this;
      this.confirmBox('删除', '确定删除该角色吗？').then(confirm => {
        if (confirm) {
          self.$axios.post('/c2/manager/user/saveRole', { mode: 'delete', id: row.id }).then(({ data }) => {
            if (data.result === 'fail') {
              self.$q.notify({
                message: data.message || '删除失败',
                color: 'negative',
                icon: 'error',
                position: 'top',
                timeout: 2000
              });
            } else {
              self.$q.notify({
                message: '删除成功',
                color: 'secondary',
                icon: 'done',
                position: 'top',
                timeout: 2000
              });
              self.search();
            }
          });
        }
      });
    },
    saveRole (formData) {
      if (!formData) return;

      const id = formData.id;
      delete formData.id;
      formData.tenant_id = this.tenant.value;

      const mode = id < 0 ? 'add' : 'edit';
      if (mode === 'add') {
        formData.rights = this.rightsTemplate;
      }

      this.$axios.post('/c2/manager/user/saveRole', { mode, id, formData }).then(({ data }) => {
        if (data.result === 'fail') {
          this.$q.notify({
            message: data.message || '保存失败',
            color: 'negative',
            icon: 'error',
            position: 'top',
            timeout: 2000
          });
        } else {
          this.$q.notify({
            message: '角色创建成功，请尽快为新角色分配权限',
            color: 'secondary',
            icon: 'done',
            position: 'top',
            timeout: 2000
          });

          this.refreshRoleOpt();
          this.search();
          if (mode === 'add') {
            this.user.selected = [];
          } else if (mode === 'edit') {
            // 发送协同，刷新用户信息
            if (this.role.selected.user_detail && this.role.selected.user_detail.length > 0) {
              this.role.selected.user_detail.forEach(row => {
                this.sendCooperation({ type: 'refresh_user' }, row.id);
              });
              this.sendCooperation({ type: 'refresh_dict', data: ['user'] });
            }
          }
        }
      });
    }
  },
  computed: {
    ...mapState(useStore, ['dictionary', 'userInfo']),
    regTimeInfo () {
      if (this.user.selected.length > 0) {
        const regdate = date.formatDate(this.user.selected[0].create_time * 1000, 'YYYY/MM/DD');
        const diffDay = date.getDateDiff(Date.now(), this.user.selected[0].create_time * 1000, 'days');
        return `${regdate} (${diffDay}天)`;
      } else {
        return '';
      }
    },
    canCopyToRole () {
      return this.tab === 'user' && !this.user.selected[0].role_id;
    }
  },
  watch: {
    'user.selected' (val) {
      if (this.tab === 'user' && val.length > 0) {
        this.parseRight(val[0].rights);
      }
    },
    'role.selected' (val) {
      if (this.tab === 'role' && val.length > 0) {
        this.parseRight(val[0].rights);
      }
    },
    tab (val) {
      this.search();
    },
    'tenant.value' (val) {
      this.user.selected = [];
      this.role.selected = [];
      this.refreshMenu();
      this.search();
    }
  }
});
</script>
